package com.kb5173.search.index.utils;

import com.kb5173.search.index.document.BaseIndexDocument;
import org.springframework.data.solr.core.query.PartialUpdate;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author Chengfei.Sun
 */
public class BeanToMapUtil {
    /**
     * 将Java对象转换成solr-data PartialUpdate类型
     *
     * @param bean
     * @param indexId
     * @return
     */
    public static PartialUpdate convertSrData(Object bean, String indexId) {
        Field[] fields = bean.getClass().getDeclaredFields();
        PartialUpdate partialUpdate = new PartialUpdate(BaseIndexDocument.ID_FIELD, indexId);
        for (int i = 0; i < fields.length; i++) {
            String name = fields[i].getName();
            Object value = getValueByName(name, bean);
            if (value != null) {
                partialUpdate.add(name, value);
            }
        }

        return partialUpdate;
    }

    /**
     * 根据属性名获取属性值
     *
     * @param fieldName
     * @param bean
     * @return
     */
    private static Object getValueByName(String fieldName, Object bean) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = bean.getClass().getMethod(getter, new Class[]{});
            Object value = method.invoke(bean, new Object[]{});
            return value;
        } catch (Exception e) {
            //TODO 异常处理
            return null;
        }
    }
}